<template>
  <el-dialog
    v-model="showDialog"
    :title="props.isEditOnlineStatus ? '上架商品' : '编辑库存'"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
    @opened="handleOpened"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
    >
      <el-form-item
        prop="tableData"
        :rules="editStockRules"
      >
        <el-table
          v-loading="loading"
          :data="tableData"
        >
          <slot name="columns">
            <product-name />
            <product-total-remain-stock />
            <product-store-remain-stock label-str="商家剩余库存" />
            <el-table-column
              label="状态"
              width="100"
            >
              <template #default="scope">
                <template v-if="props.isEditOnlineStatus">
                  <el-switch
                    v-model="scope.row.onlineStatus"
                    inline-prompt
                    :loading="scope.row.statusLoading_fe"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="上架"
                    inactive-text="下架"
                    @click="changeStatus(scope.row)"
                  />
                </template>
                <template v-else>
                  <span v-if="scope.row.onlineStatus">上架</span>
                  <span v-if="!scope.row.onlineStatus">下架</span>
                </template>
              </template>
            </el-table-column>
            <product-add-or-deduction-stock-count />
          </slot>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="showDialog = false">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { IGoodsPageRow, IStoreProductRow } from "@/api/modules/pointsMall";
import { switchProductStatus } from "@/api/pointsMall";
import ProductName from "@/components/goodsCenter/adjustProductStockColumn/ProductName.vue";
import ProductTotalRemainStock from "@/components/goodsCenter/adjustProductStockColumn/ProductTotalRemainStock.vue";
import ProductStoreRemainStock from "@/components/goodsCenter/adjustProductStockColumn/ProductStoreRemainStock.vue";
import ProductAddOrDeductionStockCount from "@/components/goodsCenter/adjustProductStockColumn/ProductAddOrDeductionStockCount.vue";
import { useEditStock } from "@/components/goodsCenter/compositions/useEditStock";

// import GoodsStatus from "@/components/goodsCenter/goodsListColumn/GoodsStatus.vue";
import { ElMessage } from "element-plus";

const props = withDefaults(
  defineProps<{
    show: boolean;
    columnProps: string[]; // 标识form中的item项都有哪些，会影响初始化时的格式化，提交时的格式化
    rowData: IGoodsPageRow; // 正在操作的商品行
    productsUrl: string; // 获取规格列表的API地址
    submitUrl: string; // 提交时的API地址
    isEditOnlineStatus: boolean;
  }>(),
  {
    show: false,
    columnProps: () => [ "name" ],
    productsUrl: "",
    submitUrl: "",
    isEditOnlineStatus: false, //是否可以库存上下架
  }
);
const emits = defineEmits([ "update:show", "confirm", "cancel" ]);
const showDialog = computed({
  get() {
    return props.show;
  },
  set(val) {
    return emits("update:show", val);
  },
});

const {
  tableData,
  loading,
  formRef,
  getTableData,
  submit,
  editStockRules,
} = useEditStock();

const form = reactive({
  tableData: tableData,
});

const handleSubmit = async () => {
  const data = tableData.value;
  // 已经上架的商品调整库存
  if (!props.isEditOnlineStatus) {
    if (props.submitUrl) {
      await submit(props.submitUrl)
    }
    showDialog.value = false;
    emits("confirm", { rowData: props.rowData, data });
    return
  }

  // 商品上架，同时显示库存调整
  const targetProduct = data.find((item) => {
    //判断库存
    const flag = item.stock > 0 || 
      Number(item.addOrDeductionStockCountSymbol_fe 
        ? item.addOrDeductionStockCount_fe 
        : (`+${item.addOrDeductionStockCount_fe}`)) || 
      item.addOrDeductionStockCount > 0
    return item.onlineStatus == 1 && flag
  })

  if (!targetProduct) {
    ElMessage.error("商品上架，需至少有一个规格的库存不为0，并且上线");
    return
  }

  // if (props.submitUrl) {
  //   await submit(props.submitUrl)
  // }
  showDialog.value = false;
  emits("confirm", { rowData: props.rowData, data });
};

//单个规格上下架
const changeStatus = async (row: IStoreProductRow) => {
  const data = {
    name: row.name,
    id: row.id,
  };
  const res = await switchProductStatus(data);

  if (res.code === 200) {
    getTableData(props.productsUrl, { id: props.rowData.id });
    ElMessage.success("操作成功");
  }
};

const handleOpened = async () => {
  getTableData(props.productsUrl, { id: props.rowData.id });
};

const handleClosed = () => {
  form.tableData = [];
};
</script>

<style scoped lang="scss"></style>
